package com.util.websocket;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: TODO
 * @Author: hechaobo
 * @Date: 2023/6/12
 **/
@ServerEndpoint("/task-ws/{taskId}")
@Component
@Slf4j
public class Websocket {
    private static ConcurrentHashMap<String,Websocket> webSocketMap = new ConcurrentHashMap();

    private Session session;
    private String Id;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("taskId") String Id) {
        this.session = session;
        this.Id = Id;
        //加入map
        webSocketMap.put(Id, this);
        log.info("当前连接数：{}",webSocketMap.size());
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从map中删除
        webSocketMap.remove(Id);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

        //群发消息
        /*for (String item : webSocketMap.keySet()) {
            try {
                webSocketMap.get(item).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }


    /**
     * 向客户端发送消息
     */
    public static void sendMessage(String message,String id){
        if(webSocketMap.get(id)==null)return;
        try {
            webSocketMap.get(id).session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void sendMessage(Object o,String id){
        if(webSocketMap.get(id)==null)return;
        try {
            webSocketMap.get(id).session.getBasicRemote().sendText(JSONUtil.parse(o).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

